package client;

import interpreter.Lexer;
import interpreter.Parser;
import interpreter.ParserBuilder;
import json.serialize.JsonPrinter;
import json.val.*;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileReader;

public class Client {
    public static String readJsonText(String filePath) throws Exception {
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuilder codeText = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            codeText.append(line);
        }
        return codeText.toString();
    }
    @Test
    public void test1() throws Exception {
        String filePath = "testFile/first.json";
        String codeText = readJsonText(filePath);
        Lexer lexer = new Lexer(codeText);
        Parser parser = new Parser(lexer);
        ObjectVal dict = (ObjectVal) parser.parse();

        JsonPrinter jsonPrinter = new JsonPrinter();
        jsonPrinter.printValue(dict);

        System.out.println("\nfriends: ");
        ArrayVal friends = (ArrayVal) dict.getValue("friends");
        for (JsonVal jsonVal : friends.getValueList()) {
            System.out.println(jsonVal);
        }

        System.out.println("\nfamily:");
        ObjectVal family = (ObjectVal) dict.getValue("family");
        jsonPrinter.printValue(family);
    }

    @Test
    public void test2() {
        ObjectVal personInfo = new ObjectVal();
        personInfo.putKeyVal("name","codeReaper");
        personInfo.putKeyVal("age",new NumVal(20));
        ArrayVal hobbies = new ArrayVal();
        hobbies.addValue("coding");
        hobbies.addValue("lol");
        hobbies.addValue("playing pingpong");
        personInfo.putKeyVal("hobbies", hobbies);

        JsonPrinter jsonPrinter = new JsonPrinter();
        jsonPrinter.printValue(personInfo);

        System.out.println("--------");
        String serializedStr = jsonPrinter.getSerializedStr(personInfo);
        System.out.println(serializedStr);
    }

    @Test
    public void test3() throws Exception {
        Parser parser = ParserBuilder.produceParser("testFile/array.json");
        ArrayVal articles = (ArrayVal) parser.parse();

        JsonPrinter jsonPrinter = new JsonPrinter();
        jsonPrinter.printValue(articles);
    }

    @Test
    public void test4() throws Exception {
        Parser parser = ParserBuilder.produceParser("testFile/tags.json");
        ArrayVal articleArray = (ArrayVal) parser.parse();

        JsonPrinter jsonPrinter = new JsonPrinter();
        jsonPrinter.printValue(articleArray);

        for (JsonVal val : articleArray.getValueList()) {
            ObjectVal obj = (ObjectVal)val;
            String tag_name = ((StringVal)obj.getValue("tag_name")).value;
            System.out.println(tag_name);
        }
    }
}
